package com.macken.wowadmin.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;

import org.apache.soap.Constants;
import org.apache.soap.SOAPException;
import org.apache.soap.encoding.SOAPMappingRegistry;
import org.apache.soap.encoding.soapenc.StringDeserializer;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;
import org.apache.soap.transport.http.SOAPHTTPConnection;
import org.apache.soap.util.xml.QName;

public class SoapUtil {
	public static String command(String cmd,String ip,int port,String user,String pass) {
		SOAPMappingRegistry smr = new SOAPMappingRegistry();
		StringDeserializer sd = new StringDeserializer();
//		org.apache.soap.util.xml.Deserializer stringDser = new org.apache.soap.encoding.soapenc.StringDeserializer();
		//		smr.mapTypes("http://schemas.xmlsoap.org/soap/encoding/", new org.apache.soap.util.xml.QName("", "Result"),
		//				null, null, stringDser);
		smr.mapTypes(Constants.NS_URI_SOAP_ENC, new QName("", "result"), null, null, sd);
		URL url=null;
		try {
			url = new URL("http://"+ip+":"+port+"/");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		Call call = new Call();
		call.setTargetObjectURI("urn:MaNGOS");
		//		call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
		call.setEncodingStyleURI("http://schemas.xmlsoap.org/soap/encoding/");
		call.setMethodName("executeCommand");

		SOAPHTTPConnection hc = new SOAPHTTPConnection();
		hc.setUserName(user);
		hc.setPassword(pass);
		call.setSOAPTransport(hc);
		call.setSOAPMappingRegistry(smr);
		Vector params = new Vector();
		//		params.addElement(new Parameter("login",String.class,"LSZEVER1",null));
		//		params.addElement(new Parameter("password",String.class,"abc,123",null));
		//		params.addElement(new Parameter("command",String.class,"account",null));
		Parameter p = new Parameter("command", String.class, cmd, null);
		params.addElement(p);
		params.addElement(new Parameter("trace", Integer.class, 1, null));
		call.setParams(params);
		String res = "";
		try {
			Response resp = call.invoke(url, "");
			if (resp == null) {

				System.out.println("null");
			}
			//System.out.println(resp.getFault().toString());
			//System.out.println(resp.getHeader().toString());
		
			Parameter ret = resp.getReturnValue();
			res = ret.getValue().toString();
		} catch (SOAPException ex) {
			res = ex.getMessage();
		} finally {
			return res;
		}
	}
}
